const express = require('express');
const { authenticateToken, requirePermissions } = require('../middleware/auth');
const Product = require('../models/Product');

const router = express.Router();

// 所有商品路由都需要认证
router.use(authenticateToken);

/**
 * 获取商品列表
 * GET /api/products
 */
router.get('/', requirePermissions(['product:view']), async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      search = '',
      category_id = null,
      status = null,
      sort = 'created_at',
      order = 'DESC'
    } = req.query;

    const result = await Product.getList({
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      search,
      category_id: category_id ? parseInt(category_id) : null,
      status,
      sort,
      order
    });

    res.success({
      products: result.products,
      total: result.total
    });

  } catch (error) {
    console.error('获取商品列表失败:', error);
    res.error('获取商品列表失败', 500, error.message);
  }
});

/**
 * 获取商品详情
 * GET /api/products/:id
 */
router.get('/:id', requirePermissions(['product:view']), async (req, res) => {
  try {
    const { id } = req.params;

    let product;
    try {
      product = await Product.getById(id);
    } catch (error) {
      // 处理商品不存在等业务异常
      if (error.message === '商品不存在') {
        return res.error('商品不存在', 404);
      }
      // 其他数据库或系统错误继续抛出
      throw error;
    }
    
    res.success(product);

  } catch (error) {
    console.error('获取商品详情失败:', error);
    res.error(error.message || '获取商品详情失败', 500);
  }
});

/**
 * 获取库存预警商品
 * GET /api/products/low-stock
 */
router.get('/alerts/low-stock', requirePermissions(['product:view']), async (req, res) => {
  try {
    const { threshold = 5 } = req.query;

    const products = await Product.getLowStockProducts(parseInt(threshold));
    res.success(products);

  } catch (error) {
    console.error('获取库存预警商品失败:', error);
    res.error('获取库存预警商品失败', 500, error.message);
  }
});

/**
 * 创建商品
 * POST /api/products
 */
router.post('/', requirePermissions(['product:create']), async (req, res) => {
  try {
    const {
      name, sku, category_id, description, price, market_price,
      stock_quantity, main_image_url, gallery_image_urls, detail_image_urls, status
    } = req.body;

    // 验证必填字段
    if (!name || name.trim() === '') {
      return res.error('商品名称不能为空', 400);
    }
    if (!sku || sku.trim() === '') {
      return res.error('商品SKU不能为空', 400);
    }
    if (!category_id) {
      return res.error('请选择商品分类', 400);
    }
    if (!price || price <= 0) {
      return res.error('商品价格必须大于0', 400);
    }
    if (!main_image_url) {
      return res.error('请上传商品主图', 400);
    }

    // 检查SKU是否重复
    const existingProduct = await Product.findBySku(sku.trim());
    if (existingProduct) {
      return res.error('SKU已存在', 400);
    }

    const product = await Product.create({
      name: name.trim(),
      sku: sku.trim(),
      category_id: parseInt(category_id),
      description: description || '',
      price: parseFloat(price),
      market_price: market_price ? parseFloat(market_price) : null,
      stock_quantity: parseInt(stock_quantity) || 0,
      main_image_url,
      gallery_image_urls: gallery_image_urls || [],
      detail_image_urls: detail_image_urls || [],
      status: status || 'draft'
    });

    res.success(product, '创建成功');

  } catch (error) {
    console.error('创建商品失败:', error);
    res.error('创建商品失败', 500, error.message);
  }
});

/**
 * 更新商品
 * PUT /api/products/:id
 */
router.put('/:id', requirePermissions(['product:edit']), async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 检查商品是否存在
    const existingProduct = await Product.findById(id);
    if (!existingProduct) {
      return res.error('商品不存在', 404);
    }

    // 如果更新SKU，检查是否重复
    if (updateData.sku && updateData.sku !== existingProduct.sku) {
      const duplicateProduct = await Product.findBySku(updateData.sku.trim());
      if (duplicateProduct && duplicateProduct.id !== parseInt(id)) {
        return res.error('SKU已存在', 400);
      }
    }

    // 处理数值字段
    if (updateData.price) {
      updateData.price = parseFloat(updateData.price);
    }
    if (updateData.market_price) {
      updateData.market_price = parseFloat(updateData.market_price);
    }
    if (updateData.stock_quantity !== undefined) {
      updateData.stock_quantity = parseInt(updateData.stock_quantity);
    }
    if (updateData.category_id) {
      updateData.category_id = parseInt(updateData.category_id);
    }

    // 调用可能抛出业务异常的Model方法
    let product;
    try {
      product = await Product.update(id, updateData);
    } catch (error) {
      // 检查是否是业务异常
      if (error.message === '没有要更新的字段') {
        return res.error(error.message, 400);
      }
      // 系统异常继续向上抛出
      throw error;
    }
    
    res.success(product, '更新成功');

  } catch (error) {
    console.error('更新商品失败:', error);
    res.error('更新商品失败', 500, error.message);
  }
});

/**
 * 删除商品
 * DELETE /api/products/:id
 */
router.delete('/:id', requirePermissions(['product:delete']), async (req, res) => {
  try {
    const { id } = req.params;

    // 检查商品是否存在
    const product = await Product.findById(id);
    if (!product) {
      return res.error('商品不存在', 404);
    }

    await Product.delete(id);
    res.success(null, '删除成功');

  } catch (error) {
    console.error('删除商品失败:', error);
    res.error(error.message || '删除商品失败', 500);
  }
});

/**
 * 批量删除商品
 * DELETE /api/products/batch
 */
router.delete('/batch', requirePermissions(['product:delete']), async (req, res) => {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.error('请选择要删除的商品', 400);
    }

    await Product.batchDelete(ids);
    res.success(null, '批量删除成功');

  } catch (error) {
    console.error('批量删除商品失败:', error);
    res.error(error.message || '批量删除失败', 500);
  }
});

module.exports = router;
